package com.example.dragon.xmf;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import com.example.dragon.common.Common;
import com.example.dragon.dialog.WaitDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONObject;

import java.util.regex.Pattern;

import okhttp3.Call;

public class LoginActivity extends AppCompatActivity {

    private EditText mtelEdit,mpassEdit;
    private WaitDialog mwaitDialog;
    private SharedPreferences sp;
    private CheckBox rem_pw, auto_login;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        sp = this.getSharedPreferences("userInfo", 0);
        initView();
    }
    public void register(View view){
        Intent intent = new Intent(this,RegisterActivity.class);
        startActivity(intent);
    }
    private void initView(){
        mtelEdit = (EditText)findViewById(R.id.tel_Edit);
        mpassEdit = (EditText)findViewById(R.id.pass_Edit);
        rem_pw = (CheckBox)findViewById(R.id.remember);
        auto_login = (CheckBox)findViewById(R.id.autologin);
        mwaitDialog = new WaitDialog(this,"3");

        if(sp.getBoolean("ISCHECK", false))
        {
            //设置默认是记录密码状态
            rem_pw.setChecked(true);
            mtelEdit.setText(sp.getString("USER_TEL", ""));
            mpassEdit.setText(sp.getString("PASSWORD", ""));
            //判断自动登陆多选框状态
            if(sp.getBoolean("AUTO_ISCHECK", false))
            {
                //设置默认是自动登录状态
                auto_login.setChecked(true);
                //跳转界面
                Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                LoginActivity.this.startActivity(intent);
                LoginActivity.this.finish();
            }
        }
        rem_pw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                if (rem_pw.isChecked()) {

                    System.out.println("记住密码已选中");
                    sp.edit().putBoolean("ISCHECK", true).commit();

                }else {

                    System.out.println("记住密码没有选中");
                    sp.edit().putBoolean("ISCHECK", false).commit();

                }

            }
        });

        //监听自动登录多选框事件
        auto_login.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                if (auto_login.isChecked()) {
                    System.out.println("自动登录已选中");
                    sp.edit().putBoolean("AUTO_ISCHECK", true).commit();

                } else {
                    System.out.println("自动登录没有选中");
                    sp.edit().putBoolean("AUTO_ISCHECK", false).commit();
                }
            }
        });
    }
    public void Login(View view){
        String tel = mtelEdit.getText().toString();
        String pass = mpassEdit.getText().toString();
        if (matchPhone(tel)){
            if (pass.equals("")){
                Toast.makeText(getApplicationContext(),"请输入密码",Toast.LENGTH_SHORT).show();
            }else {
                doLogin(tel,pass);
            }
        }else {
            Toast.makeText(getApplicationContext(),"请输入正确手机号",Toast.LENGTH_SHORT).show();
        }
    }

    public void foragetPass(View view){
        startActivity(new Intent(this,RegisterActivity.class));
    }

    private void doLogin(final String tel, final String pass) {
        mwaitDialog.show();
        OkHttpUtils.post()
                .url(Common.URL+"login")
                .addParams("mob",tel)
                .addParams("pass",pass)
                .addParams("group","1")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("res",e.toString());
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            Log.i("sun", response);
                            mwaitDialog.dismiss();
                            JSONObject jsonObject = new JSONObject(response);
                            int code = jsonObject.getInt("code");
                            if (code==200){
                                SharedPreferences.Editor editor = sp.edit();
                                JSONObject dates  = jsonObject.getJSONObject("datas");
                                editor.putString("user_id",dates.getString("user_id"));
                                editor.putString("mobile",dates.getString("mobile"));
                                editor.putString("token",dates.getString("token"));
                                editor.putString("name",dates.getString("name"));
                                editor.putString("avatar",dates.getString("avatar"));
                                editor.commit();
                                if(rem_pw.isChecked())
                                {
                                    //记住用户名、密码、
                                    editor.putString("USER_TEL", tel);
                                    editor.putString("PASSWORD",pass);
                                    editor.commit();
                                }
                                startActivity(new Intent(LoginActivity.this,MainActivity.class));
                                LoginActivity.this.finish();
                                android.widget.Toast.makeText(LoginActivity.this, code+"", android.widget.Toast.LENGTH_SHORT).show();
                            }else {
                                showMessageDialog("登录信息",jsonObject.getString("message"),"确认");
                                Toast.makeText(LoginActivity.this, code+"", android.widget.Toast.LENGTH_SHORT).show();
                            }
                        }catch (Exception e){

                        }
                    }
                });
    }


    public void showMessageDialog(CharSequence title, CharSequence message,String msg) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton(msg, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.show();
    }

    private boolean matchPhone(String text) {
        if (Pattern.compile("^((1[358][0-9])|(14[57])|(17[0678]))\\d{8}$").matcher(text).matches()) {
            return true;
        }
        return false;
    }
}

